package com.yuandengta.yomall.ware.service.impl;

import com.yuandengta.common.constant.WareConstant;
import com.yuandengta.yomall.ware.entity.PurchaseDetailEntity;
import com.yuandengta.yomall.ware.service.PurchaseDetailService;
import com.yuandengta.yomall.ware.service.WareSkuService;
import com.yuandengta.yomall.ware.vo.MergeVO;
import com.yuandengta.yomall.ware.vo.PurchaseDoneVO;
import com.yuandengta.yomall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.ware.dao.PurchaseDao;
import com.yuandengta.yomall.ware.entity.PurchaseEntity;
import com.yuandengta.yomall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnReceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode()).or()
                        .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求-采购单
     * @param mergeVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (StringUtils.isEmpty(purchaseId)) {
            // 新增
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setPriority(1);
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 合并采购单
        // 确认采购单状态是 0,1 才可以合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {

            List<Long> items = mergeVO.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> detailEntities = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            detailService.updateBatchById(detailEntities);

            // 采购单更新时间
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
    }

    /**
     * 领取采购单
     * @param ids 采购单id集合
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void receivePurchase(List<Long> ids) {
        // 1.确认当前采购单是新建或已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(purchaseEntity -> {
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {
            // 设置采购单的状态为已领取
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());

        // 2.批量修改采购单的状态
        this.updateBatchById(purchaseEntities);

        // 3.修改采购项的状态
        purchaseEntities.forEach(purchaseEntity -> {
            // 根据采购单id获取采购项
            List<PurchaseDetailEntity> detailEntities =
                    detailService.listDetailByPurchaseId(purchaseEntity.getId());

            List<PurchaseDetailEntity> collect = detailEntities.stream().map(detailEntity -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(detailEntity.getId());
                entity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());

            // 批量修改采购项状态
            detailService.updateBatchById(collect);
        });
    }

    /**
     * 完成采购单
     * @param purchaseDoneVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        // 1.修改采购项状态
        List<PurchaseDetailEntity> updateList = new ArrayList<>();
        boolean flag = true;
        for (PurchaseItemDoneVO itemDoneVO : purchaseDoneVO.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (itemDoneVO.getStatus() == WareConstant.PurchaseDetailEnum.FAILED.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(itemDoneVO.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.FINISHED.getCode());
                // 2.将成功采购的商品入库
                PurchaseDetailEntity detailEntity = detailService.getById(itemDoneVO.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
            }

            purchaseDetailEntity.setId(itemDoneVO.getItemId());
            updateList.add(purchaseDetailEntity);
        }
       detailService.updateBatchById(updateList);

        // 3.修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVO.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISHED.getCode()
                : WareConstant.PurchaseStatusEnum.ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}